package com.liu.webstore.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author LiuYumei
 * @Date 2022/7/19 9:44 AM
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/cookie/set")
    public String setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("code", UUID.randomUUID().toString());
        cookie.setMaxAge(60 * 10);
        cookie.setPath("/demo");
        response.addCookie(cookie);
        return "set cookie";
    }

    @GetMapping("/cookie/get")
    public String getCookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get cookie";
    }

    @GetMapping("/session/set")
    public String setSession(HttpSession session) {
        session.setAttribute("id", 1);
        session.setAttribute("name", "zhangsan");
        return "set session";
    }

    @GetMapping("/session/get")
    public String getSession(HttpSession session) {
        return JSONObject
                .toJSONString(session.getAttribute("id") + ":::" + session.getAttribute("name"));
    }
}
